<?php

include_once 'validador.class.php';
include_once 'operacionesBD.php';

define('SALT', '$5$jediphpavanzadoisournewsalt$');


if(isset($_POST)){
    if(isset($_POST['name'])) {
        echo json_encode(testName($_POST['name']));
    }
    if(isset($_POST['password'])) {
        echo json_encode(testPass($_POST['password']));
    }
    if(isset($_POST['email'])) {
        echo json_encode(testMail($_POST['email']));
    }
    if(isset($_POST['oldPassword'])) {
        echo json_encode(testOriginalPass($_POST['oldPassword']));
    }
}

function testOriginalPass($password){
     $opBD = operacionesBD::getInstance('localhost', 'root', '', 'musica');
     $password = crypt($password, SALT);
     $query = "SELECT * FROM users WHERE username={$_POST['username']} AND password=$password";
     $result = $opBD->consultar($query);
     return $result;
}

function testName($name){
    $validador = new Validador();
    $result = $validador->valida('name', $name, '/\w/');
    if ($result == $name){
        $opBD = operacionesBD::getInstance('localhost', 'root', '', 'musica');
        $query = "Select * FROM users WHERE username='{$name}'";
        $result = $opBD->consultar($query);
        if (count($result) == 0)
            return 'Ok!';
    }
    return 'Incorrect value';
}

function testPass($password){
    $complexity = testComplexity($password);
    return $complexity;
}

function testMail($mail){
    $validador = new Validador();
    $result = $validador->valida('name', strtolower($mail), '/^[_\w-]+(\.[_\w-]+)*@[\w-]+(\.[\w-]+)*(\.[a-zA-Z]{2,3})$/');
    if ($result == $mail){
        $opBD = operacionesBD::getInstance('localhost', 'root', '', 'musica');
        $query = "Select * FROM users WHERE mail='{$mail}'";
        $result = $opBD->consultar($query);
        if (count($result) == 0)
            return 'Ok!';
    }
    return 'Incorrect value';
}

function testComplexity($password){
    if(strlen($password) >= 8){
        $regexp = '/[a-zA-Z]+/';
        if (preg_match($regexp, $password)){
            $regexp = '/[[a-zA-Z]+[0-9]*[\W]*]/';
            if (preg_match($regexp, $password)){
                $regexp = '/[[a-zA-Z]+[0-9]+[\W]+]/';
                if (preg_match($regexp, $password)){
                    return 4;
                }
            }
            return 3;
        }
        return 2;
    }
    return 1;
     //muy mala < 8 caracteres
                            // mala -> solo letras
                            // normal -> letras y numeros o simbolos
                            // buena -> letras, numeros o simbolos

}
?>
